<?php
namespace app\admin\controller;

use think\Controller;
use app\admin\model\ClassifyModel;
use think\Db;
use think\Request;

class Classify extends Controller
{
  
  public function index(){
    return '2333333';
  }

  // 获取分类数据
  public function selAll(){
    // $allData=json_decode(file_get_contents("php://input"));
    $result= Db::table('gjc_classify')->field('cid,c_name as title,fid')->select();
    if($result){
      return res(1000,'',$result);
    }else{
      return res(1001,'查询失败');
    } 
    // var_dump($result);
  }

  // 分类修改
  public function edit(){
    $request = Request::instance();
    $newID = (int)$request->post('id');
    $newName = $request->post('newName');
    // 引入model层
    $model = new ClassifyModel;
    $repet = $model->classifySelID($newID);
    $repetTitle = $repet['c_name']; 
    // 判断是否重复   
    if($newName == $repetTitle){
      return res(1010,'您提交的修改内容重复，无法修改');
    }else{
      $result = $model->classifyEdit($newID,$newName);
      // 判断是否修改成功
      if($result){
        return res(1000,'修改成功');
      }else{
        return res(1001,'修改失败');
      }

    }
    
    
    
  }
  
  //分类删除
  public function del(){
    $request=Request::instance();
    $delId = $request->post()['idList'];
    $flag = false;
    // 查询所选分类id是否有商品
    foreach($delId as $key =>$v){
      $id = $v;
      $goods=Db::table('gjc_goods')->where('cid',$id)->select();
      if($goods){
        $flag = true;
      }
    }
    // 分类id拥有对应商品时无法删除
    if($flag == true){
      return res(1011,'所选分类已有对应商品，无法删除');
    }else{
      // 引入model层方法
      $model = new ClassifyModel;
      $result = $model->classifyDel($delId);
      // 判断是否删除成功
      if($result){
        return res(1000,'删除成功');
      }else{
        return res(1001,'删除失败');
      }
    }

  }

  // 分类添加
  public function add(){
    $request=Request::instance();
    $fid = (int)$request->post('fid');
    $nowName = $request->post('nowName');
    // 引入model层方法
    $model=new ClassifyModel();
    // 查找数据库是否有相同分类名
    $repet = $model->classifySelName($nowName);
    if($repet){
      return res(1010,'您添加的分类已存在');
    }else{
      $result = $model->classifyAdd($fid,$nowName);
      // 判断是否修改成功
      if($result==0){
        return res(1000,'添加成功');
      }else{
        return res(1001,'添加失败');
      }
    }
    
    
  }

}